<template>

	<!-- <ibalbal-tabbar :active="active" @changeActiveIndex="changeActiveIndex" :config="iconConfig"></ibalbal-tabbar> -->

	<view class="BaiDuMap">
		<ibalbal-tabbar :active="1" @changeActiveIndex="changeActiveIndex" :config="iconConfig"></ibalbal-tabbar>
		<view class="page" v-if="cha">
			<view class="action">
				<view>
					<image src="/static/center4/setting.png"></image>
				</view>
			</view>
			<view class="user">
				<image class="avatar" src="/static/center4/avatar.png"></image>
				<view class="name">
					<text>{{this.showID}}</text>
					<text>{{this.showType}}</text>
				</view>
				<image class="right" src="/static/center4/right.png"></image>
			</view>

			<view class="card">
				<view class="menu">
					<view class="item2" v-for="v in menus1" :key="v.id" @click="handleItemClick(v.id)">
						<image :src="v.icon"></image>
						<view>{{v.name}}</view>
						<image class="arrow" v-if="v.arrow" src="/static/center1/right.png"></image>
					</view>
				</view>
			</view>
		</view>

		<view class="BaiDuMap" v-else>
			<baidu-map :center="center" :zoom="zoom" :scroll-wheel-zoom="true" style="width: 100%; height: 100%"
				@ready="handler" @click="getClickInfo" @moving="syncCenterAndZoom" @moveend="syncCenterAndZoom"
				@zoomend="syncCenterAndZoom" :min-zoom=5>


				<!-- 必须给容器指高度，不然地图将显示在一个高度为0的容器中，看不到 -->
				<bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
				<bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true"
					:autoLocation="true"></bm-geolocation>

				<view class="btn-win"><wyb-button class="btn" width="360rpx" type="filled" @click="clikChoseLine()">
						<text class="button-text">选择路线</text></wyb-button></view>
				<fui-toast ref="toast"></fui-toast>

				<div>
					<!-- 显示人当前位置 -->
					<bm-marker :position="{lng: autoLocationCenter.lng, lat: autoLocationCenter.lat}"
						:icon="{url: require('@/static/img/校车 (2).png'), size: {width: 32, height: 32}}">
					</bm-marker>
				</div>

				<div>
					<bm-marker v-for="(marker, index) in carStations" :key="index"
						:position="{lng: marker.stationLng, lat: marker.stationLat}" :dragging="false">
						<bm-label :content="marker.stationName" :offset="labelOffset[index]" />
					</bm-marker>
				</div>


				<div v-if="lineChose">
					<bm-driving :start="convertToLocation(this.carLineInfo[this.nowChoseLine].startStation)"
						:end="convertToLocation(this.carLineInfo[this.nowChoseLine].endStation)" location="南宁"
						:waypoints="this.waypoints"></bm-driving>
				</div>

				<fui-drawer :show="show2" direction="left" @close="closeDrawer()">
					<view class="fui-scroll__view">
						<view class="fui-title">左侧菜单栏</view>
						<scroll-view scroll-y style="height: 720rpx;">
							<view>
								<fui-list-cell v-for="(item,index) in carLineInfo" :key="index" @click="test(index)">
									路线{{index+1}}
								</fui-list-cell>
							</view>
						</scroll-view>
						<view class="fui-btn__box">
							<fui-button type="warning" width="400rpx" height="84rpx" text="关闭菜单栏" bold
								@click="closeDrawer(2)">
							</fui-button>
						</view>
					</view>
				</fui-drawer>
			</baidu-map>
		</view>
	</view>

</template>
<script>
	import store from '../../store/index';
	import IbalbalTabbar from "@/components/ibalbal-tabbar/ibalbal-tabbar.vue";

	export default {
		components: {
			IbalbalTabbar
		},
		data() {
			return {
				showID: 123345,
				showType: "司机",
				menus1: [{
						id: 1,
						name: '我的订单',
						icon: '/static/center4/book.png',
						arrow: true
					},
					{
						id: 2,
						name: '我的评价',
						icon: '/static/center4/kefu.png',
						arrow: true
					},
				],
				cha: false,
				active: 0,
				iconConfig: [{
					icon: "icon-gps_o",
					name: "应用"
				}, {
					icon: "icon-my",
					name: "我的"
				}],
				show2: false,
				lineChose: false,
				// itemList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
				carStations: [], //车站的全部信息

				nowChoseLine: -1,
				waypoints: [],
				carLineInfo: [], //全部路线以供选择

				autoLocationCenter: {
					lng: 108.297348,
					lat: 22.846808,
				},
				// 地址信息
				address: null,
				center: {
					lng: 0,
					lat: 0
				},
				//地图展示级别
				zoom: 18,
				customIcon: null,
			};
		},
		computed: {
			labelOffset() {
				return this.carStations.map(marker => {
					const labelWidth = marker.stationName.length * 6; // 假设每个字符宽度为15px
					return {
						width: -labelWidth / 2,
						height: 30
					}; // 根据字体长度计算偏移量
				});
			}
		},
		mounted() {
			setInterval(() => {
				// this.getLocation();
			}, 5000);
			if (this.$store.state.hasLogin == true) {
				this.showID = this.$store.state.userdata[1];
				console.log("inhereCh");
			}
		},
		onLoad() {

			uni.request({
				url: 'http://localhost:8080/app/car/station',
				// url: 'http://127.0.0.1:4523/m1/3961673-0-default/map/palceList',
				method: 'GET',
				success: res => {
					if (res.statusCode === 200 && res.data.code === 0) {
						this.carStations = res.data.carStation;
					} else {
						console.log('请求失败');
					}
				},
				fail: err => {
					console.log('请求失败', err);
				}
			});
			uni.request({
				url: 'http://localhost:8080/app/car/lineAll',
				method: 'GET',
				success: res => {
					if (res.statusCode === 200 && res.data.code === 0) {
						this.carLineInfo = res.data.result;
					} else {
						console.log('请求失败');
					}
				},
				fail: err => {
					console.log('请求失败', err);
				}
			});
		},
		methods: {
			handleItemClick(menuItem) {
				switch (menuItem) {
					case 1:
						uni.navigateTo({
							url: '/pages/order/driverorder', // 使用绝对路径
						});
						break;
					case 2:
						uni.navigateTo({
							url: '/pages/order/driver', // 使用绝对路径
						});
						break;
					default:
						break;
				}

			},
			getLocation() { //获得现在位置
				const that = this;
				var geolocation = new BMap.Geolocation();
				geolocation.getCurrentPosition(function(r) {
					if (this.getStatus() == BMAP_STATUS_SUCCESS) {
						that.autoLocationCenter.lng = r.longitude;
						that.autoLocationCenter.lat = r.latitude;
						console.log(that.autoLocationCenter.lat);
						console.log(that.autoLocationCenter.lng);
						//this.updateCarLocation(this.$store.state.userdata, this.autoLocationCenter.lat, this.autoLocationCenter.lng)
					} else {
						alert("failed" + this.getStatus());
					}
				});
			},
			test(index) {
				this.waypoints = [];
				this.nowChoseLine = index;
				// console.log(this.carLineInfo[index]);
				for (let key in this.carLineInfo[index]) {
					if (key.startsWith('passStation')) {
						if (this.carLineInfo[index][key] !== "null") {
							let coords = this.carLineInfo[index][key].split(', ');
							let alng = coords[0].split(':')[1];
							let alat = coords[1].split(':')[1];
							this.waypoints.push({
								lng: alng,
								lat: alat
							});
						}
					}
				}
				this.lineChose = true;

				this.closeDrawer();
			},
			showDrawer() {
				this.show2 = true;
			},
			closeDrawer() {
				this.show2 = false;
			},
			clikChoseLine() {
				this.updateCarLocation(this.$store.state.userdata[1], this.autoLocationCenter.lat, this.autoLocationCenter
					.lng)
				this.showDrawer();
				this.center = this.autoLocationCenter;
			},
			handler({
				BMap,
				map
			}) {
				this.center.lng = 116.404;
				this.center.lat = 39.915;
				this.zoom = this.zoom;
			},
			getClickInfo(e) {
				// 创建地理编码实例
				const myGeo = new BMap.Geocoder();
				// 根据坐标逆解析地址
				myGeo.getLocation(new BMap.Point(e.point.lng, e.point.lat), (result) => {
					console.log(result, "result-->>>>");
					if (result) {
						this.address = result.address;
					}
				});
				this.center.lng = e.point.lng;
				this.center.lat = e.point.lat;
			},
			syncCenterAndZoom(e) {
				console.log(e.target, 'e.target-->>>>')
				const {
					lng,
					lat
				} = e.target.getCenter();
				this.zoom = e.target.getZoom();
				this.center = e.target.getCenter();
			},
			updateCarLocation(uid, lat, lng) {
				// 定义请求的URL
				const url = 'http://localhost:8080/app/car/update';

				// 构建请求的参数对象
				const myParams = {
					uid: uid, // 这里传入用户ID
					lat: lat, // 这里传入纬度
					lng: lng // 这里传入经度
				};

				// 发送PUT请求
				uni.request({
					url: 'http://localhost:8080/app/car/update',
					data: myParams, // 传入请求的参数
					method: 'PUT', // 指定请求方法为PUT
					header: {
						'content-type': "application/x-www-form-urlencoded",
					},
					success: (res) => {
						// 请求成功的处理
						console.log(myParams.uid);
						console.log(myParams.lat);
						console.log('更新车辆位置信息成功:', res);
						// 这里可以根据实际情况进行处理，比如更新页面信息或者提示用户
					},
					fail: (error) => {
						// 请求失败的处理
						console.error('更新车辆位置信息失败:', error);
						// 这里可以进行错误提示或者错误处理
					}
				});
			},
			convertToLocation(str) {
				let a = str.split(', ');
				let b = a[0].split(':');
				let c = a[1].split(':');
				// console.log(c[1]);
				return {
					lng: parseFloat(b[1]),
					lat: parseFloat(c[1])
				};
			},
			changeActiveIndex(index) {
				if (index == 2) this.cha = true;
				else this.cha = false;
			},
		},
	};
</script>

<style scoped lang="scss">
	@import url("./css/dmap.css");

	.page {
		background: #f5f5f5;
		min-height: 100vh;

		.action {
			display: flex;
			justify-content: flex-end;
			padding: 10rpx;
			background: #fff;

			view {
				padding: 10rpx;
				margin: 0 10rpx;
				border-radius: 8rpx;
				width: 45rpx;
				height: 45rpx;

				&:active {
					background: #ccc;
				}

				image {
					width: 45rpx;
					height: 45rpx;
				}
			}
		}

		.user {
			display: flex;
			align-items: center;
			padding: 25rpx;
			background: #fff;

			&:active {
				background: #f0f0f0;
			}

			.avatar {
				width: 90rpx;
				height: 90rpx;
				border-radius: 50%;
			}

			.right {
				width: 30rpx;
				height: 30rpx;
			}

			.name {
				flex-grow: 1;
				display: flex;
				flex-direction: column;
				padding-left: 20rpx;

				text {
					&:nth-child(1) {
						font-size: 16px;
						font-weight: bold;
					}

					&:nth-child(2) {
						font-size: 12px;
						color: #777;
					}
				}
			}
		}

		.card {
			background: #fff;
			box-sizing: border-box;
			width: 700rpx;
			margin: auto;
			padding: 15rpx;
			margin-top: 20rpx;
			border-radius: 12rpx;

			.menu {

				.item2 {
					display: flex;
					height: 100rpx;
					align-items: center;
					padding: 0 20rpx;
					box-sizing: border-box;
					width: 700rpx;

					&:active {
						background: #f0f0f0;
					}

					image {
						height: 45rpx;
						width: 45rpx;
					}

					view {
						font-size: 14px;
						color: #444;
						padding-left: 15rpx;
						box-sizing: border-box;
						width: calc(100% - 100rpx);
					}

					.arrow {
						width: 26rpx;
						height: 26rpx;
					}
				}
			}
		}

	}
</style>